package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ShopMapper shopMapper;
    @Resource
    private CacheClient cacheClient;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR
            = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {
        // 缓存穿透
        // Shop shop = queryWithPassThrough(id);
//        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY,id,
//                Shop.class,this::getById,RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);
        // 互斥锁解决缓存击穿问题
        Shop shop = queryWithMutex(id);
        // 逻辑过期解决缓存击穿问题
//        Shop shop = cacheClient.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY,id,
//                Shop.class,this::getById,RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);
        // 判断店铺信息是否为空
        if (shop == null) {
            return Result.fail("error");
        }

        // 返回商户信息
        return Result.ok(shop);
    }

    /*// 逻辑过期解决缓存击穿问题
    private Shop queryWithLogicalExpire(Long id) {
        // 从redis中查询店铺信息
        String shopJson = stringRedisTemplate.opsForValue()
                .get(RedisConstants.CACHE_SHOP_KEY+id);
        if (StrUtil.isBlank(shopJson)) {
            // 未命中，返回空
            return null;
        }
        // 如果命中
        // 判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        // 未过期
        if(LocalDateTime.now().isBefore(redisData.getExpireTime())){
            // 返回商铺信息
            return shop;
        }
        // 过期
        String queryKey = RedisConstants.LOCK_SHOP_KEY+id;
        // 尝试获取互斥锁
        boolean flag = keyLock(queryKey);
        if (flag) {

            CACHE_REBUILD_EXECUTOR.submit( ()->{
                // 如果获取成功，开启独立线程
                try{
                    //重建缓存
                    this.saveShop2Redis(id,20L);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    unLock(queryKey);
                }
            });
        }
        // 返回数据
        return shop;
    }*/

    /*public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
        // Thread.sleep(200);
        String key = RedisConstants.CACHE_SHOP_KEY+id;
        Shop shop = shopMapper.selectById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }*/

    // 互斥锁解决缓存击穿
    private Shop queryWithMutex(Long id){
        // 从redis中查询店铺信息
        String shopJson = stringRedisTemplate.opsForValue()
                .get(RedisConstants.CACHE_SHOP_KEY+id);
        if (StrUtil.isNotBlank(shopJson)) {
            // redis中有的话返回
            Shop shop = JSONUtil.toBean(shopJson,Shop.class);
            return shop;
        }
        // 判断是否为空
        if(shopJson != null){
            return null;
        }
        // 创建互斥锁
        String queryKey = RedisConstants.LOCK_SHOP_KEY+id;
        Shop shop = null;
        try {
            boolean flag = keyLock(queryKey);
            if (!flag) {
                // 如果创建失败，则进入等待
                Thread.sleep(10);
                queryWithMutex(id);
            }
            // 没有的话从数据库中查询
            shop = shopMapper.selectById(id);
            // 如果不存在，返回错误信息
            if(shop == null){
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,"");
                return null;
            }
            // 将数据库中查询的信息存到redis中
            stringRedisTemplate.opsForValue()
                    .set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(shop));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            unLock(queryKey);
        }
       // 返回数据
        return shop;
    }

    /*// 避免缓存穿透代码
    private Shop queryWithPassThrough(Long id){
        // 从redis中查询店铺信息
        String shopJson = stringRedisTemplate.opsForValue()
                .get(RedisConstants.CACHE_SHOP_KEY+id);
        if (StrUtil.isNotBlank(shopJson)) {
            // redis中有的话返回
            Shop shop = JSONUtil.toBean(shopJson,Shop.class);
            return shop;
        }
        *//* 查询到的数据是否为空
         当数据库不存在当前查询数据时，会将该数据存入redis，值为空
         上面已经过滤掉了值不为空且不为null，这里判断值是否不为null
         不为null就代表是空，也就是数据库中不存在
         直接返回数据，防止频繁访问数据库*//*
        if(shopJson != null){
            return null;
        }
        // 没有的话从数据库中查询
        Shop shop = shopMapper.selectById(id);
        // 如果不存在，返回错误信息
        if(shop == null){
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,"");
            return null;
        }
        // 将数据库中查询的信息存到redis中
        stringRedisTemplate.opsForValue()
                .set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(shop));
        return shop;
    }*/

    // 创建锁
    private boolean keyLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1",
                10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    // 释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
    /**
     * 更新店铺信息
     * @param shop
     * @return
     */
    @Override
    public Result update(Shop shop) {
        // 先判断店铺id是否为空
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空!");
        }
        // 更新数据库信息
        updateById(shop);
        // 删除redis中的数据
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+id);
        return Result.ok();
    }

    /**
     * 按照距离分页查询店铺
     * @param typeId
     * @param current
     * @param x
     * @param y
     * @return
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 若x或y为空，则根据类型分页查询
        if(x==null || y==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 计算分页参数
        long from  = (current - 1)*DEFAULT_BATCH_SIZE;
        long end = current*DEFAULT_BATCH_SIZE;
        // 根据类型查询该类型的所有店铺
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate
                .opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance()
                        .limit(end));
        // 解析id
        if(results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        // 若大小小于from，则所有商铺信息都已经查询
        if(list.size()<=from){
            return Result.ok(Collections.emptyList());
        }
        // 获取ids
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> map = new HashMap<>(list.size());
        // 保存id，以及id和对应的距离
        list.stream().skip(from).forEach(result->{
            String id = result.getContent().getName();
            ids.add(Long.valueOf(id));
            map.put(id,result.getDistance());
        });
        // 根据id获取店铺信息
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids)
                .last("ORDER BY FIELD(id," + idStr + ")").list();
        // 将距离填进商铺信息
        for (Shop shop : shops) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());
        }
        // 返回数据
        return Result.ok(shops);
    }
}
